package com.itheima.controller;

import com.itheima.Role;
import com.itheima.UserInfo;
import com.itheima.service.IRoleService;
import com.itheima.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    /**
     * 查询所有用户
     * @return
     */
    @RequestMapping("/findAll.do")
    public ModelAndView findAll(){


        ModelAndView mv = new ModelAndView();

        List<UserInfo> userList = userService.findAll();

        mv.addObject("userList",userList);
        mv.setViewName("user-list");
        return mv;

    }

    /**
     * 添加用户
     * @param userInfo
     * @return
     */
    @Secured("ROLE_ADMIN")
//    @RolesAllowed("ADMIN")
    @RequestMapping("/save.do")
    public String save(UserInfo userInfo){

        userService.save(userInfo);

        return "redirect:findAll.do";
    }

    /**
     * 根据用户id查询用户详情
     * @param id
     * @return
     */
    @RequestMapping("/findById.do")
    public ModelAndView findById(@RequestParam(name = "id",required = true) String id){

        ModelAndView mv = new ModelAndView();

        UserInfo userInfo = userService.findUserById(id);

        mv.addObject("user",userInfo);
        mv.setViewName("user-show");

        return mv;
    }

    /**
     * 此方法用于查找要操作的用户及可以添加的角色，参数是要操作的用户id
     * @param userId
     * @return
     */
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id",required = true) String userId){

        UserInfo user = userService.findUserById(userId);
        List<Role> roleList = roleService.findOtherRole(userId);
        ModelAndView mv = new ModelAndView();

        mv.addObject("user",user);
        mv.addObject("roleList",roleList);
        mv.setViewName("user-role-add");
        return mv;

    }

    /**
     * 此方法用于在用户与角色之间建立关系，参数userId代表要操作的用户id,参数ids代表的是角色id数组
     * @param userId
     * @param roleIds
     * @return
     */
    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(String userId,String[] roleIds){
        userService.addRoleToUser(userId,roleIds);
        return "redirect:findAll.do";
    }
}
